package org.offsync.nio

import java.nio.channels.{SelectableChannel => JavaSelectableChannel}
import java.nio.channels.{SelectionKey => JavaSelectionKey}
import java.nio.channels.{Selector => JavaSelector}
import java.nio.channels.spi.{SelectorProvider => JavaSelectorProvider}
import org.offsync.util.DisposableBase
import org.offsync.util.Trace.trace

case class SelectableChannel(
    protected val channel: JavaSelectableChannel) extends InterestParty with DisposableBase {
  def blockingLock: Object = channel.blockingLock
  
  def configureBlocking(block: Boolean): JavaSelectableChannel = channel.configureBlocking(block)
  
  def isBlocking: Boolean = channel.isBlocking
  
  def isRegistered: Boolean = channel.isRegistered
  
  def keyFor(selector: Selector): JavaSelectionKey = channel.keyFor(selector.selector)
  
  def provider: JavaSelectorProvider = channel.provider
  
  def validOps: Int = channel.validOps

  def register(selector: Selector, f: Option[Throwable] => Unit): JavaSelectionKey = {
    return channel.register(selector.selector, selector.op, f)
  }

  protected override def onDispose(): Unit = {
    try {
      cancelKeys()
      Thread.sleep(100)
      channel.close()
    } catch {
      case e => e.printStackTrace(System.err)
    } finally {
      super.onDispose()
    }
  }
}
